package com.uchedao.vehicledetection.activity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.JsonObject;
import com.uchedao.mybaselibrary.activity.BaseActivity;
import com.uchedao.mybaselibrary.entity.VersionInfo;
import com.uchedao.mybaselibrary.utils.JsonUtils;
import com.uchedao.mybaselibrary.utils.SystemUtils;
import com.uchedao.mybaselibrary.utils.UpdateApk;
import com.uchedao.mybaselibrary.view.dialog_for_ios.ZAlertDialog;
import com.uchedao.vehicledetection.R;
import com.uchedao.vehicledetection.config.Api;
import com.uchedao.vehicledetection.config.UserInfoManager;
import com.uchedao.vehicledetection.network.HttpRequest;
import com.uchedao.vehicledetection.utils.ToastUtil;
import com.uchedao.vehicledetection.view.FastCheckCarView;
import com.uchedao.vehicledetection.view.NormalCheckCarView;
import com.uchedao.vehicledetection.view.carlist.m_service.updateDBService;
import com.uchedao.vehicledetection.view.widget.quickactionpopuwindow.QuickAction;
import com.uchedao.vehicledetection.view.widget.quickactionpopuwindow.QuickActionList;
import com.uchedao.vehicledetection.view.widget.quickactionpopuwindow.QuickActionWidget;
import com.uchedao.vehicledetection.view.widget.quickactionpopuwindow.QuickActionWidget.OnQuickActionClickListener;

import java.util.HashMap;
import java.util.Map;

/**
 * 主页
 */
public class CheckCarActivity extends BaseActivity implements View.OnClickListener {

    /**
     * 3秒内点击后退两次退出程序
     */
    private final static long EXIT_APP_TIME_INTERVAL = 3 * 1000;
    /**
     * 点击返回键的间隔时间
     */
    private long clickBackTime = 0;
    private QuickActionList mGrid;
    private FastCheckCarView mFastView;
    private NormalCheckCarView mNormalView;
    private RadioButton rb_check_car, rb_new_car;

    private int currentId = 1;

    @Override
    protected String getActivityTag() {
        return "CheckCarActivity";
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_check_car;
    }

    @Override
    protected void initView() {
        mFastView = (FastCheckCarView) findViewById(R.id.activity_check_car_fast_view);
        mNormalView = (NormalCheckCarView) findViewById(R.id.activity_check_car_normal_view);
        rb_check_car = (RadioButton) findViewById(R.id.rb_check_car);
        rb_new_car = (RadioButton) findViewById(R.id.rb_new_car);
        mGrid = new QuickActionList(this);
    }

    @Override
    protected void initData() {
        requestVersion(false);
        initQuickActionList();
    }

    @Override
    protected void initListener() {

        findViewById(R.id.activity_check_car_menu_ibtn).setOnClickListener(this);

        mGrid.setOnQuickActionClickListener(mActionListener);

        rb_check_car.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (currentId == 2 && b) {
                    showTabView(1);
                }
            }
        });
        rb_new_car.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (currentId == 1 && b) {
                    showTabView(2);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        showTabView(currentId);
    }

    private void initQuickActionList() {

//        mGrid.addQuickAction(getString(R.string.my_cars));
        mGrid.addQuickAction(new QuickAction(getResources().getDrawable(R.mipmap.check_menu_cars_ic), getString(R.string.my_cars)));
//        mGrid.addQuickAction(getString(R.string.draft));
        mGrid.addQuickAction(new QuickAction(getResources().getDrawable(R.mipmap.check_menu_draft_ic), getString(R.string.draft)));
//        mGrid.addQuickAction(getString(R.string.checked_cars));
        mGrid.addQuickAction(new QuickAction(getResources().getDrawable(R.mipmap.check_menu_checked_cars_ic), getString(R.string.checked_cars)));
//        mGrid.addQuickAction(getString(R.string.update_cars_db));
        mGrid.addQuickAction(new QuickAction(getResources().getDrawable(R.mipmap.check_menu_update_cars_db_ic), getString(R.string.update_cars_db)));
//        mGrid.addQuickAction(getString(R.string.update_apk));
        mGrid.addQuickAction(new QuickAction(getResources().getDrawable(R.mipmap.check_menu_system_ic), getString(R.string.update_apk)));
        mGrid.addQuickAction(new QuickAction(getResources().getDrawable(R.mipmap.check_menu_loginout_ic), String.format("%s,%s", getString(R.string.login_out), UserInfoManager.getUSERNAME())));
    }

    /**
     * 快捷栏item点击事件
     */
    private OnQuickActionClickListener mActionListener = new OnQuickActionClickListener() {
        public void onQuickActionClicked(QuickActionWidget widget, int position) {

            switch (position) {
                case 0://
                    startActivity(new Intent(CheckCarActivity.this, MyCarSourceActivity.class));
                    break;
                case 1:

                    startActivity(new Intent(CheckCarActivity.this, DraftsActivity.class));
                    break;
                case 2:
                    startActivity(new Intent(CheckCarActivity.this, InspectedCarSourceActivity.class));
                    break;
                case 3://更新车型库
                    Intent server = new Intent(CheckCarActivity.this, updateDBService.class);
                    startService(server);
                    Intent check = new Intent(CheckCarActivity.this, CheckCarActivity.class);
                    check.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                    PendingIntent pendingIntent = PendingIntent.getActivity(CheckCarActivity.this, 0, check, 0);
                    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    Notification noti = new NotificationCompat.Builder(CheckCarActivity.this)
                            .setTicker("数据库更新").setContentTitle("车检单")
                            .setSmallIcon(R.mipmap.ic_launcher).setContentText("正在更新车型数据库")
                            .setContentIntent(pendingIntent).setAutoCancel(true).build();
                    manager.notify(1, noti);
                    break;
                case 4:
                    requestVersion(true);
                    break;
                case 5://退出登陆
                    UserInfoManager.saveSTATE(false);
                    Intent intent = new Intent(CheckCarActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();
                    break;

            }
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.activity_check_car_menu_ibtn:
                mGrid.show(view);
                break;
        }
    }

    /**
     * 切换UI
     */
    private void showTabView(int tabId) {
        switch (tabId) {
            case 1:
            default:
                currentId = 1;
                mNormalView.setVisibility(View.VISIBLE);
                mFastView.setVisibility(View.GONE);
                rb_check_car.setChecked(true);
                rb_new_car.setChecked(false);
                mNormalView.init(this);
                break;
            case 2:
                currentId = 2;
                mNormalView.setVisibility(View.GONE);
                mFastView.setVisibility(View.VISIBLE);
                rb_check_car.setChecked(false);
                rb_new_car.setChecked(true);
                break;
        }
    }

    VersionInfo info;

    /**
     * 检测版本号
     */
    private void requestVersion(final boolean isShowToast) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("app", "check");
        Request request = HttpRequest.getRequest(HttpRequest.GET, Api.Action.APP_VERSION, map
                , new Response.Listener<JsonObject>() {
            @Override
            public void onResponse(JsonObject response) {
                try {
                    info = JsonUtils.objectFromJson(response, VersionInfo.class);
                    int _now_code = SystemUtils.getVersionCode(CheckCarActivity.this);
                    if (info.getVersion_code() > _now_code) {
                        new ZAlertDialog.Builder(CheckCarActivity.this)
                                .setTitle("版本更新")
                                .setMessage(String.format("当前版本号：V%s\n最新版本：V%s\n更新内容：%s\n%s"
                                        , SystemUtils.getVersionName(CheckCarActivity.this)
                                        , info.getVersion_name()
                                        , info.getNote()
                                        , info.getConstraint() == 1 ? "此版本必须更新!" : "是否更新?"))
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        new UpdateApk(CheckCarActivity.this, info).showDownloadDialog();
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //关闭Dialog
                                        if (info.getConstraint() == 1) {
                                            new UpdateApk(CheckCarActivity.this, info).showDownloadDialog();
                                        }
                                    }
                                }).show();
                    } else {
                        if (isShowToast) {
                            Toast.makeText(CheckCarActivity.this, getString(R.string.version_is_max), Toast.LENGTH_SHORT).show();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (isShowToast) {
                        Toast.makeText(CheckCarActivity.this, getString(R.string.version_is_max), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (isShowToast) {
                    Toast.makeText(CheckCarActivity.this, "获取版本信息失败！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        addQueue(request);
    }

    @Override
    public void onBackPressed() {
        eixt();
    }

    /**
     * 退出程序
     */
    private void eixt() {
        if (clickBackTime == 0) {
            clickBackTime = System.currentTimeMillis();
            ToastUtil.showToast(
                    getResources().getString(R.string.common_message_exit_app), false);
        } else {
            final long nowTime = System.currentTimeMillis();
            if (nowTime - clickBackTime > EXIT_APP_TIME_INTERVAL) {
                // 超过3秒，时间置为当前时间
                clickBackTime = nowTime;
                ToastUtil.showToast(getResources()
                        .getString(R.string.common_message_exit_app), false);
            } else {
                finish();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mFastView.clear();
    }
}
